import { Button, Card, message } from 'antd';
import { connect } from 'dva';
import React, { useRef, useState } from 'react';
import CodeEditor from '@/components/CodeEditor';
import request from '@/utils/request';

function CompressionTool({ height }) {
  const leftRef = useRef();
  const rightRef = useRef();
  const [leftLoading, setLeftLoading] = useState(false);
  const [rightLoading, setRightLoading] = useState(false);

  const handleUncompress = () => {
    const left = leftRef.current.getValue();
    if (!left) {
      message.error('待解压字符串不能为空');
      return;
    }
    setLeftLoading(true);
    request
      .post('/compression/uncompress', { data: { input: left } })
      .then(({ output }) => {
        message.success('解压缩成功');
        rightRef.current.setValue(output);
      })
      .finally(() => setLeftLoading(false));
  };

  const handleCompress = () => {
    const right = rightRef.current.getValue();
    if (!right) {
      message.error('待压缩字符串不能为空');
      return;
    }
    setRightLoading(true);
    request
      .post('/compression/compress', { data: { input: right } })
      .then(({ output }) => {
        message.success('压缩成功');
        leftRef.current.setValue(output);
      })
      .finally(() => setRightLoading(false));
  };

  return (
    <div style={{ display: 'flex', gap: 8, alignItems: 'center', height }}>
      <CodeEditor
        placeholder="请输入待解压文本..."
        ref={leftRef}
        mode="text"
        style={{ flex: '1 0 auto' }}
        height={height}
        wrap
      />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <Button icon="right" type="primary" onClick={handleUncompress} disabled={leftLoading}>
          解压缩
        </Button>
        <Button icon="left" onClick={handleCompress} disabled={rightLoading}>
          压缩
        </Button>
      </div>
      <CodeEditor
        placeholder="请输入待压缩json..."
        ref={rightRef}
        formatOnSetValue={false}
        mode="json"
        style={{ flex: '1 0 auto' }}
        height={height}
      />
    </div>
  );
}

export default connect(({ setting }) => ({
  height: setting.size.height,
}))(CompressionTool);
